function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["tableStyle", "categoryStyle", "style", "labelConfig", "uploadRef"];
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { forwardRef, useContext, useMemo, useRef, useState } from 'react';
import { Button, Divider, message, ModalContext, Space, Table, Tabs } from "../../../../functionalComponent";
import { Layout, iup, useRefCallback } from "../../../../util";
import { AttachmentProvider, useAttachment } from "../../AttachmentContext";
import { DownloadRecordModal, FileView, LabelSelect, RemarkModal, Toolbar } from "../../components";
import { getFileSize } from "../../util";
import "./index.less";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var shareTypeOptions = [{
  label: '自己',
  value: 'self'
}, {
  label: '人员',
  value: 'empno'
}, {
  label: '部门',
  value: 'dept'
}];
var attachmentCategoryOptions = [{
  label: '单据附件',
  key: 'attach'
}, {
  label: '审批后附件',
  key: 'approvedAttach'
}
// { label: '工作流附件', value: 'workFlowAttach' },
// { label: '来源单据附件', value: 'oriBizAttach' },
];
export var OriginTableAttachment = function OriginTableAttachment(props) {
  var _labelConfig$style;
  var _props$style = props.style,
    style = _props$style === void 0 ? {} : _props$style,
    categoryStyle = props.categoryStyle,
    _props$tableStyle = props.tableStyle,
    tableStyle = _props$tableStyle === void 0 ? {} : _props$tableStyle,
    _props$uploadRef = props.uploadRef,
    uploadRef = _props$uploadRef === void 0 ? useRef(null) : _props$uploadRef,
    labelConfig = props.labelConfig;
  var _useAttachment = useAttachment(),
    beforeUploadValidate = _useAttachment.beforeUploadValidate,
    accept = _useAttachment.accept,
    maxCount = _useAttachment.maxCount,
    disabled = _useAttachment.disabled,
    actions = _useAttachment.actions,
    permission = _useAttachment.permission,
    attachmentRecordList = _useAttachment.attachmentRecordList,
    loading = _useAttachment.loading,
    isReady = _useAttachment.isReady,
    attachmentFileList = _useAttachment.attachmentFileList,
    approved = _useAttachment.approved,
    uploading = _useAttachment.uploading,
    onUploadStateChange = _useAttachment.onUploadStateChange,
    onContentChanged = _useAttachment.onContentChanged;
  var _useContext = useContext(ModalContext),
    ins = _useContext.ins,
    params = _useContext.params;
  // 表格配置项
  var _useState = useState('attach'),
    _useState2 = _slicedToArray(_useState, 2),
    attachType = _useState2[0],
    setAttachType = _useState2[1];
  var _useState3 = useState({
      attach: [],
      approvedAttach: []
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    checkedListMap = _useState4[0],
    setCheckedListMap = _useState4[1];
  var checkedList = useMemo(function () {
    return checkedListMap[attachType];
  }, [checkedListMap, attachType]);
  var _useState5 = useState(),
    _useState6 = _slicedToArray(_useState5, 2),
    curRow = _useState6[0],
    setCurRow = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    remarkVisible = _useState8[0],
    setRemarkVisible = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    downloadRecordVisible = _useState10[0],
    setDownloadRecordVisible = _useState10[1];
  var _tableConfig = [{
    title: '附件名称',
    dataIndex: 'asrName',
    width: 210,
    flex: 1,
    tooltip: true,
    filter: true,
    render: function render(_ref) {
      var row = _ref.row;
      var isFail = row.status === 'fail';
      var uploaded = row.status === 'done' || row.status === undefined;
      var isPreview = uploaded && (permission === null || permission === void 0 ? void 0 : permission.preview) !== 2 && actions.isPreview(row.asrName || row.fileName);
      return /*#__PURE__*/_jsx("span", {
        className: "attachment-flex-center ".concat(isFail ? 'upload-failed' : ''),
        children: /*#__PURE__*/_jsx(FileView, {
          iconPosition: "right",
          isPreview: isPreview,
          data: {
            fileName: row.asrName || row.fileName,
            fileSize: row.originFileSize || row.fileSize,
            status: row.status,
            percent: row.percent
          },
          handlePreview: function handlePreview() {
            if ((permission === null || permission === void 0 ? void 0 : permission.preview) === 0) {
              message.error('没有预览权限，无法预览');
              return;
            }
            row.asrFid && actions.preview(row.asrFid);
          }
        })
      });
    }
  }, {
    title: '附件状态',
    dataIndex: 'asrFlag',
    width: 80,
    flex: 1,
    render: function render(_ref2) {
      var value = _ref2.value;
      return ['未保存', '已保存'][+value];
    }
  }, {
    title: '标签',
    dataIndex: 'label',
    width: (labelConfig === null || labelConfig === void 0 || (_labelConfig$style = labelConfig.style) === null || _labelConfig$style === void 0 ? void 0 : _labelConfig$style.width) || 150,
    flex: 1,
    render: function render(_ref3) {
      var value = _ref3.value,
        row = _ref3.row;
      return /*#__PURE__*/_jsx(LabelSelect, {
        labelConfig: _objectSpread(_objectSpread({}, labelConfig), {}, {
          defaultValue: value,
          disabled: disabled,
          style: _objectSpread(_objectSpread({}, labelConfig === null || labelConfig === void 0 ? void 0 : labelConfig.style), {}, {
            width: '100%'
          })
        }),
        fileId: row.asrFid,
        onChangeCallback: onContentChanged
      });
    }
  }, {
    title: '备注',
    dataIndex: 'asrRemark',
    width: 80,
    flex: 1,
    tooltip: true
  }, {
    title: '附件大小',
    dataIndex: 'originFileSize',
    width: 80,
    format: {
      type: 'number',
      formatter: function formatter(_ref4) {
        var value = _ref4.value;
        return getFileSize(value);
      }
    },
    flex: 1
  }, {
    title: '上传人',
    dataIndex: 'userName',
    width: 80,
    flex: 1
  }, {
    title: '上传时间',
    dataIndex: 'asrFilldt',
    width: 150,
    flex: 1,
    render: function render(_ref5) {
      var value = _ref5.value;
      return value && iup.formatDate(new Date(value), 'YYYY-MM-DD HH:mm:ss');
    }
  },
  // {
  //   title: '共享方式',
  //   dataIndex: 'shareType',
  //   width: 80,
  //   flex: 1,
  //   render: ({ value, row }) => (
  //     <Select
  //       className="share-type-select"
  //       options={shareTypeOptions}
  //       defaultValue={value && value.split(',')[0]}
  //       bordered={false}
  //       onSelect={(v) => handleChangeShareType(v, row).then(getTableAttach)}
  //     />
  //   )
  // },
  // {
  //   title: '共享给',
  //   dataIndex: 'sharedOneName',
  //   width: 80,
  //   flex: 1,
  //   tooltip: true
  // },
  {
    title: '操作',
    dataIndex: 'options',
    flex: 1,
    width: 150,
    fixed: 'right',
    render: function render(_ref6) {
      var row = _ref6.row;
      var uploaded = row.status === 'done' || row.status === undefined;
      if (!uploaded) return null;
      return /*#__PURE__*/_jsxs(Space, {
        size: 0,
        split: /*#__PURE__*/_jsx(Divider, {
          type: "vertical",
          style: {
            borderLeft: '1px solid var(--primary-color)'
          }
        }),
        children: [/*#__PURE__*/_jsx("a", {
          style: {
            color: 'var(--primary-color)'
          },
          onClick: function onClick() {
            setCurRow(row);
            setRemarkVisible(true);
          },
          children: "\u4FEE\u6539\u5907\u6CE8"
        }), /*#__PURE__*/_jsx("a", {
          style: {
            color: 'var(--primary-color)'
          },
          onClick: function onClick() {
            setCurRow(row);
            setDownloadRecordVisible(true);
          },
          children: "\u4E0B\u8F7D\u8BB0\u5F55"
        })]
      });
    }
  }];
  var filterAttachmentCategoryOptions = useMemo(function () {
    if (+approved === 1 || (attachmentRecordList === null || attachmentRecordList === void 0 ? void 0 : attachmentRecordList.findIndex(function (item) {
      return +item.approved === 1;
    })) > -1) {
      return attachmentCategoryOptions;
    } else {
      return attachmentCategoryOptions.filter(function (item) {
        return item.key !== 'approvedAttach';
      });
    }
  }, [approved, attachmentRecordList]);
  var onToolbarClick = useRefCallback(function (action) {
    switch (action) {
      case 'delete':
        if (!checkedList.length) {
          message.warning('请选择至少一行进行删除');
          return;
        }
        if (attachType !== 'approvedAttach' && +approved === 1) {
          message.error('已审批的单据只能删除审批后附件');
          return;
        }
        actions.delete(checkedList);
        break;
      case 'download':
        if (!checkedList.length) {
          message.warning('请选择至少一行进行下载');
        } else {
          actions.download(checkedList);
        }
        break;
      case 'zipDownload':
        actions.zipDownload();
        break;
    }
  });
  var dataSource = useMemo(function () {
    var _checkedList = checkedListMap[attachType];
    var checkedNames = _checkedList.map(function (item) {
      return item.fileName;
    });
    return attachmentFileList.map(function (v) {
      return _objectSpread(_objectSpread({}, v), {}, {
        checked: checkedNames.includes(v.fileName)
      });
    });
  }, [attachmentFileList, checkedListMap, attachType]);
  var tableConfig = iup.isNullOrEmpty(labelConfig) ? _tableConfig.filter(function (col) {
    return col.dataIndex !== 'label';
  }) : _tableConfig;
  return /*#__PURE__*/_jsxs(Layout, {
    className: "iup-table-attachment",
    style: style,
    direction: "row",
    children: [/*#__PURE__*/_jsxs(Layout.Flex, {
      className: "iup-table-attachment-content",
      children: [/*#__PURE__*/_jsx(Toolbar, {
        accept: accept,
        uploadRef: uploadRef,
        uploading: uploading,
        permission: permission,
        onUploadStateChange: onUploadStateChange,
        onUploaded: onContentChanged,
        onBeforeUpload: beforeUploadValidate,
        isReady: isReady,
        onToolbarClick: onToolbarClick
      }), /*#__PURE__*/_jsx("div", {
        style: {
          margin: '5px 0 '
        }
      }), filterAttachmentCategoryOptions.length > 1 ? /*#__PURE__*/_jsx(Tabs, {
        fitHeight: false,
        size: "small",
        defaultActiveKey: filterAttachmentCategoryOptions[0].key,
        items: filterAttachmentCategoryOptions,
        onChange: function onChange(v) {
          return setAttachType(v);
        },
        tabBarStyle: {
          backgroundColor: '#F9FAFB',
          padding: '0 22px 3px'
        }
      }) : null, /*#__PURE__*/_jsx(Layout.Flex, {
        className: "attachment-table-container",
        style: tableStyle,
        children: /*#__PURE__*/_jsx(Table, {
          remember: false,
          checkbox: true,
          headerMenu: false,
          rowHeight: 40,
          loading: loading,
          onCheckedChange: function onCheckedChange(list) {
            return setCheckedListMap(function (state) {
              return _objectSpread(_objectSpread({}, state), {}, _defineProperty({}, attachType, list));
            });
          },
          columns: tableConfig,
          dataSource: dataSource
        }, attachType)
      }), params !== null && params !== void 0 && params.isModal ? /*#__PURE__*/_jsxs("div", {
        style: {
          display: 'flex',
          margin: '15px 5px 5px',
          justifyContent: 'flex-end'
        },
        children: [/*#__PURE__*/_jsx(Button, {
          onClick: function onClick() {
            return params === null || params === void 0 ? void 0 : params.handleCancel(ins);
          },
          style: {
            width: 84,
            marginRight: 10
          },
          children: "\u53D6\u6D88"
        }), /*#__PURE__*/_jsx(Button, {
          onClick: function onClick() {
            return params === null || params === void 0 ? void 0 : params.handleOk(ins);
          },
          type: "primary",
          style: {
            width: 84
          },
          children: "\u786E\u5B9A"
        })]
      }) : null]
    }), /*#__PURE__*/_jsx(RemarkModal, {
      data: curRow,
      visible: remarkVisible,
      disabled: disabled,
      onCancel: function onCancel() {
        return setRemarkVisible(false);
      },
      onSaved: onContentChanged
    }), /*#__PURE__*/_jsx(DownloadRecordModal, {
      data: curRow,
      visible: downloadRecordVisible,
      setVisible: setDownloadRecordVisible
    })]
  });
};
export var TableAttachment = /*#__PURE__*/forwardRef(function (_ref7, ref) {
  var tableStyle = _ref7.tableStyle,
    categoryStyle = _ref7.categoryStyle,
    style = _ref7.style,
    labelConfig = _ref7.labelConfig,
    uploadRef = _ref7.uploadRef,
    rest = _objectWithoutProperties(_ref7, _excluded);
  return /*#__PURE__*/_jsx(AttachmentProvider, _objectSpread(_objectSpread({}, rest), {}, {
    ref: ref,
    children: /*#__PURE__*/_jsx(OriginTableAttachment, {
      style: style,
      tableStyle: tableStyle,
      uploadRef: uploadRef,
      categoryStyle: categoryStyle,
      labelConfig: labelConfig
    })
  }));
});